package com.community.web.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.common.exception.NeusoftException;
import com.community.common.result.ResultCodeEnum;
import com.community.model.entity.Carts;
import com.community.model.entity.GoodsStore;
import com.community.web.user.service.CartsService;
import com.community.web.user.mapper.CartsMapper;
import com.community.web.user.service.GoodsStoreService;
import com.community.web.user.vo.CartInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author admin
 * @description 针对表【carts】的数据库操作Service实现
 * @createDate 2024-07-02 10:56:56
 */
@Service
public class CartsServiceImpl extends ServiceImpl<CartsMapper, Carts>
        implements CartsService {

    @Autowired
    private GoodsStoreService storeService;

    @Autowired
    private CartsMapper mapper;


    @Override
    public void add(Carts carts) {
        //判断购物车内是否有同一门店同一商品的条目,有就合并
        LambdaQueryWrapper<Carts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Carts::getUserId, carts.getUserId());
        queryWrapper.eq(Carts::getGoodsNo, carts.getGoodsNo());
        queryWrapper.eq(Carts::getStoreNo, carts.getStoreNo());
        Carts one = super.getOne(queryWrapper);
        if (one != null) {
            carts.setId(one.getId());
            carts.setAmount(one.getAmount() + carts.getAmount());
            updateNumber(carts);
        } else {
            storeService.checkStock(carts);
            mapper.insert(carts);
        }

    }

    @Override
    public List<CartInfoVo> selectByUserId(Long userId) {
        return mapper.selectByUserId(userId);
    }

    @Override
    public void updateNumber(Carts carts) {
        storeService.checkStock(carts);
        LambdaUpdateWrapper<Carts> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Carts::getId, carts.getId());
        updateWrapper.set(Carts::getAmount, carts.getAmount());
        super.update(updateWrapper);
    }
}




